package api

import (
	"context"
	"github.com/gin-gonic/gin"
	"net/http"
	"service_base_shop_api/user_web/global"
	"service_base_shop_api/user_web/proto"
	"service_base_shop_api/user_web/utils"
	"strconv"
)


//获取
func GetSessionKey(ctx *gin.Context)  {
	parms := utils.Requests(ctx,[]string{"code"})

	GetOpenIdData,err := global.UserSrvClient.GetOpenId(context.Background(),&protopb.GetOpenIdReq{Code: parms["code"]})
	if err != nil {
		utils.HandleGrpcErrorToHttp(err,ctx)
		return
	}
	ctx.JSON(http.StatusOK,gin.H{"status":1,"openid":GetOpenIdData.Openid,"session_key":GetOpenIdData.SessionKey})
}

//登录
func AuthLogin(ctx *gin.Context)  {
	parms := utils.Requests(ctx,[]string{"openid","SessionId","gender","NickName","HeadUrl"})
	gender,_ := strconv.Atoi(parms["gender"])
	AuthLoginData,err := global.UserSrvClient.AuthLogin(context.Background(),&protopb.AuthLoginReq{Openid: parms["openid"],NickName: parms["NickName"],HeadUrl: parms["HeadUrl"],Gender: int32(gender),SessionKey: parms["SessionId"]})
	if err != nil {
		utils.HandleGrpcErrorToHttp(err,ctx)
		return
	}


	JwtData,JwtErr := global.JwtClient.CreateToken(context.Background(),&protopb.CreateTokenReq{ID: uint64(AuthLoginData.ID),NickName: AuthLoginData.NickName})
	if JwtErr != nil {
		ctx.JSON(http.StatusNotFound, gin.H{
			"status":0,
			"msg": "颁发token失败",
		})
	}
	ctx.JSON(http.StatusOK, gin.H{
		"status":1,
		"data":gin.H{
			"HeadUrl":AuthLoginData.HeadUrl,
			"ID":AuthLoginData.ID,
			"NickName":AuthLoginData.NickName,
			"Token":JwtData.Token,
		},
	})
}